<template>
	<view
		class="container text-hide"
		:class="[isImgList ? 'row-wrap' : 'text-center py-3-1']"
		:style="{
			'margin-bottom': (isImgList ? (innerMb - vSpace) : innerMb) + 'px',
		}"
	>
		<template v-if="isImgList">
			<view
				class="rounded-n"
				v-for="(el, i) in innerData"
				:key="i"
				:style="{
					width: itemWidth + 'px',
					'margin-right': (i + 1) % columnNum === 0 ? 0 : hSpace + 'px',
					'margin-bottom': vSpace + 'px',
				}"
				hover-class="opacity-80"
				hover-start-time="0"
				hover-stay-time="0"
				@click="handleClick(el, i)"
			>
				<image
					:mode="imgMode"
					:src="el.src || FALLBACK_IMG"
					:style="{ width: itemWidth + 'px', height: itemWidth + 'px' }"
					@error="handleError(el)"
				/>
			</view>
		</template>
		<text v-else class="text-m color-disable"> 暂无数据 </text>
	</view>
</template>

<script>
//'margin-right': (i + 1) % columnNum === 0 ? 0 : hSpace + 'px',
import { getCurrentInstance, ref, onMounted, computed, watch, nextTick } from 'vue';
import { FALLBACK_IMG } from '../../../utils/media';
export default {
	props: {
		//[{src: ''}]
		data: Array,
		hSpace: {
			default: 24,
			type: Number,
		},
		vSpace: {
			default: 24,
			type: Number,
		},
		//不支持heightFix
		imgMode: {
			default: 'aspectFit',
			type: String,
		},
		columnNum: {
			default: 3,
			type: Number,
		},
		//rpx
		marginBottom: Number,
	},
	setup(props, ctx) {
		const { ctx: curCtx } = getCurrentInstance();
		const itemWidth = ref(0);
		const hSpace = ref(uni.upx2px(props.hSpace));
		const vSpace = ref(uni.upx2px(props.vSpace));
		function handleData(data){
			if(!data){
				return [];
			}
			return data.map((el) => {
				if(typeof el == 'string'){
					return {
						src: el
					}
				}
				return el;
			});
		}
		const innerData = ref(handleData(props.data));
		watch(
			() => props.data,
			(v) => {
				innerData.value = handleData(v);
				nextTick(() => {
					resize();
				});
			}
		);
		function resize() {
			uni
				.createSelectorQuery()
				.in(curCtx)
				.select('.container')
				.boundingClientRect((data) => {
					itemWidth.value = parseInt((data.width - (props.columnNum - 1) * hSpace.value) / props.columnNum);
				})
				.exec();
		}
		onMounted(() => {
			resize();
		});
		const isImgList = computed(() => Array.isArray(props.data) && props.data.length > 0);
		function handleError(el) {
			el.src = FALLBACK_IMG;
		}
		const innerMb = ref(uni.upx2px(props.marginBottom || 0));
		function handleClick(el, i){
			ctx.emit("touch", el);
			const urls = innerData.value.filter((item) => !!item.src).map((item) => item.src);
			if(urls.length === 0) return;
			uni.previewImage({
				current: i,
				urls,
			});
		}
		return {
			itemWidth,
			hSpace,
			vSpace,
			isImgList,
			handleError,
			innerMb,
			innerData,
			handleClick,
			FALLBACK_IMG,
		};
	},
};
</script>
